USE [WGRUS-phone]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER dbo.CustomerEventTrigger 
   ON  dbo.Customer 
   AFTER INSERT
AS

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @Action as nvarchar(10);
    SET @Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED)
                         AND EXISTS(SELECT * FROM DELETED)
                        THEN 'UPDATE'  -- Set Action to Updated.
                        WHEN EXISTS(SELECT * FROM INSERTED)
                        THEN 'INSERT'  -- Set Action to Insert.
                        WHEN EXISTS(SELECT * FROM DELETED)
                        THEN 'DELETE'  -- Set Action to Deleted.
                        ELSE 'FAILED' -- Skip. It may have been a "failed delete".   
                    END)

	IF SYSTEM_USER <> 'mule' --IS NULL
	BEGIN
		INSERT INTO dbo.CustomerEvent
		([TelefonNr],[Navn],[Gade],[PostNr],[By],[Oprettet],[Email],[EVENT])
		SELECT 
		[TelefonNr],[Navn],[Gade],[PostNr],[By],[Oprettet],[Email],@Action AS [Event]
		FROM INSERTED;
	END
END
GO

